//
//  JSKeyboardView.m
//  JigSaw
//
//  Created by mykoma on 15/3/2.
//  Copyright (c) 2015年 LITB. All rights reserved.
//

#import "JSKeyboardView.h" 
#import "UIColor+Help.h"
#import "AMBlurView.h"
#define INIT_INPUT_HEIGHT (33.6)
#define INIT_TOP_VIEW_HEIGHT (33.6)

@implementation JSKeyboardViewModel

@end

@interface JSKeyboardView ()

@property (nonatomic, weak) IBOutlet AMBlurView * topView;
@property (nonatomic, weak) IBOutlet AMBlurView * bottomView;
@property (nonatomic, weak) IBOutlet UIButton * inputTypeBtn;
@property (nonatomic, weak) IBOutlet UIButton * okBtn;
@property (nonatomic, weak) IBOutlet UITextView * inputTV;
@property (nonatomic, weak) IBOutlet UITableView * fontTableView;
@property (nonatomic, weak) IBOutlet UIView * colorView;
@property (nonatomic, weak) IBOutlet UIButton * xinqingBtn;
@property (nonatomic, weak) IBOutlet UIButton * color1Btn;
@property (nonatomic, weak) IBOutlet UIButton * color2Btn;
@property (nonatomic, weak) IBOutlet UIButton * color3Btn;
@property (nonatomic, weak) IBOutlet UIButton * color4Btn;
@property (nonatomic, weak) IBOutlet UIButton * color5Btn;
@property (nonatomic, weak) IBOutlet UIButton * color6Btn;
@property (nonatomic, weak) IBOutlet UIButton * color7Btn;
@property (nonatomic, assign) KeyboardInputType inputType;
@property (nonatomic, strong) IBOutlet UIView   * placeholdView;
//@property (nonatomic, strong)        UIView   * tempView;

@property (nonatomic, weak) UIButton * latestChooseBtn;

@end

@implementation JSKeyboardView

+ (JSKeyboardView *)keyboardView
{
    return [[NSBundle mainBundle] loadNibNamed:@"JSKeyboardView" owner:self options:nil][0];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
//    self.inputTV.contentInset = UIEdgeInsetsMake(-10, 0, -10, 0);
//    self.tempView = self.placeholdView;
    self.bottomView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.6];
    self.topView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.6];
    self.fontTableView.tableFooterView = [[UIView alloc] init];
    [self updateInputStatus:self.inputType];
    [self roundButton:self.color1Btn];
    [self roundButton:self.color2Btn];
    [self roundButton:self.color3Btn];
    [self roundButton:self.color4Btn];
    [self roundButton:self.color5Btn];
    [self roundButton:self.color6Btn];
    [self roundButton:self.color7Btn];
    self.topView.backgroundColor = [UIColor colorWithHex:0x171819 alpha:0.7];
    self.colorView.backgroundColor = [UIColor clearColor];
    self.fontTableView.backgroundColor = [UIColor colorWithHex:0xffffff alpha:0.1];
    self.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.frame.size.height);
    self.inputTV.layer.cornerRadius = 4;
    
    @weakify(self);
    [[self.inputTypeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self);
         KeyboardInputType newInputType = !self.inputType;
         [self updateInputStatus:newInputType];
     }];
    [[self.okBtn rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self);
         if (self.okBlock) {
             self.okBlock();
         }
         [self removeFromSuperview];
         [[UIApplication sharedApplication].keyWindow endEditing:YES];
     }];
    [[self.xinqingBtn rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self);
         if (self.xinqingBlock) {
             self.xinqingBlock();
         }
     }];
    self.fontTableView.dataSource=self;
    self.fontTableView.delegate=self;
    self.fontTableView.separatorInset = UIEdgeInsetsZero;
    self.fontTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.inputTV.rac_textSignal subscribeNext:^(id x) {
        @strongify(self);
        [self updateInputViewHeight];
        if (self.textChangeBlock) {
            self.textChangeBlock(x);
        }
    }];
}

- (void)setContentText:(NSString*)string
{
    self.inputTV.text = string;
    [self layoutIfNeeded];
}

- (void)setViewModel:(JSKeyboardViewModel *)viewModel
{
    _viewModel = viewModel;
    self.inputTV.text = viewModel.inputText;
    [self layoutIfNeeded];
    [self updateInputViewHeight];
}

- (void)resetButtons
{
    [self setButton:self.color1Btn state:NO];
    [self setButton:self.color2Btn state:NO];
    [self setButton:self.color3Btn state:NO];
    [self setButton:self.color4Btn state:NO];
    [self setButton:self.color5Btn state:NO];
    [self setButton:self.color6Btn state:NO];
    [self setButton:self.color7Btn state:NO];
}

- (void)roundButton:(UIButton *)button
{
    button.layer.cornerRadius = 13.5f;
}

- (void)setButton:(UIButton *)button state:(BOOL)choosed
{
    NSMutableString * mStr = [@"fontColor" mutableCopy];
    [mStr appendFormat:@"%ld", button.tag];
    choosed ? [mStr appendString:@"_selected"] : nil;
    UIImage * image = [UIImage imageNamed:mStr];
    [button setImage:image forState:UIControlStateNormal];
}

- (UIColor *)colorForButton:(UIButton *)button
{
    if (button == self.color1Btn) {
        return [UIColor colorWithRed:237.0f/255.0f green:105.0f/255.0f blue:128.0f/255.0f alpha:1.0f];
    } else if (button == self.color2Btn) {
        return [UIColor colorWithRed:229.0f/255.0f green:180.0f/255.0f blue:96.0f/255.0f alpha:1.0f];
    } else if (button == self.color3Btn) {
        return [UIColor colorWithRed:76.0f/255.0f green:152.0f/255.0f blue:115.0f/255.0f alpha:1.0f];
    } else if (button == self.color4Btn) {
        return [UIColor colorWithRed:78.0f/255.0f green:159.0f/255.0f blue:189.0f/255.0f alpha:1.0f];
    } else if (button == self.color5Btn) {
        return [UIColor colorWithRed:180.0f/255.0f green:125.0f/255.0f blue:81.0f/255.0f alpha:1.0f];
    } else if (button == self.color6Btn) {
        return [UIColor colorWithRed:137.0f/255.0f green:137.0f/255.0f blue:137.0f/255.0f alpha:1.0f];
    } else if (button == self.color7Btn) {
        return [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.viewModel.fontCellModels.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSKeyboardFontCellModel * cellModel = self.viewModel.fontCellModels[indexPath.row];
    NSString * identifier = [NSString stringWithFormat:@"JSKeyboardFontCell%ld", cellModel.type];
    JSKeyboardFontCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"JSKeyboardFontCell" owner:self options:nil][cellModel.type];
    }
    cell.cellModel = cellModel;
    @weakify(self);
    cell.downloadBlock = ^ (JSKeyboardFontCell * cell)
    {
        @strongify(self);
        if (self.downloadFontBlock) {
            self.downloadFontBlock(indexPath.row);
        }
    };
    
    cell.cancelBlock = ^ (JSKeyboardFontCell * cell)
    {
        @strongify(self);
        if (self.cancelFontBlock) {
            self.cancelFontBlock(indexPath.row);
        }
    };
    UIView* line = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 0.5, cell.frame.size.width, 0.5)];
    line.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.1];
    [cell addSubview:line];
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    JSKeyboardFontCellModel * cellModel = self.viewModel.fontCellModels[indexPath.row];
    if (cellModel.type == JSKeyboardFontCellTypeNormal || cellModel.type == JSKeyboardFontCellTypeDownloadDone) {
        if (self.chooseFontBlock) {
            self.chooseFontBlock(indexPath.row);
        }
    }
}

- (void)updateInputStatus:(KeyboardInputType)type
{
    self.inputType = type;
    if (type == KeyboardInputTypeFont) {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        [self.inputTypeBtn setImage:[UIImage imageNamed:@"keyboard_icon"] forState:UIControlStateNormal];
        [self.inputTypeBtn setImage:[UIImage imageNamed:@"keyboard_click_icon"] forState:UIControlStateHighlighted];
        self.xinqingBtn.hidden = YES;
    }
    else{
        [self.inputTV becomeFirstResponder];
        [self.inputTypeBtn setImage:[UIImage imageNamed:@"font_icon"] forState:UIControlStateNormal];
        [self.inputTypeBtn setImage:[UIImage imageNamed:@"font_icon_click"] forState:UIControlStateHighlighted];
        self.xinqingBtn.hidden = NO;
    }
}

- (void)updateSystemKeyboardRect:(CGRect)rect
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.topView.frame = CGRectMake(CGRectGetMinX(self.topView.frame), CGRectGetHeight(self.frame) - CGRectGetHeight(rect) - CGRectGetHeight(self.topView.frame), CGRectGetWidth(self.topView.frame), CGRectGetHeight(self.topView.frame));
    });
}

- (void)dismiss
{
    [self removeFromSuperview];
}

- (IBAction)chooseColorClicked:(UIButton *)sender
{
    [self resetButtons];
    [self setButton:sender state:YES];
    if (self.chooseColorBlock) {
        self.chooseColorBlock([self colorForButton:sender]);
    }
}

- (void)updateInputViewHeight
{
    static CGFloat maxHeight = 51;
    CGSize contentSize = self.inputTV.contentSize;
    CGFloat actHeight = MIN(maxHeight, contentSize.height);
//    if (contentSize.height < maxHeight) {
        self.topView.frame = CGRectMake(0, CGRectGetMaxY(self.topView.frame) - actHeight - 18,
                                        CGRectGetWidth(self.topView.frame), actHeight + 18);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.inputTV.frame = CGRectMake(CGRectGetMinX(self.inputTV.frame), CGRectGetMinY(self.inputTV.frame),
                                            CGRectGetWidth(self.inputTV.frame), actHeight);
            self.xinqingBtn.frame = CGRectMake(CGRectGetMinX(self.xinqingBtn.frame), CGRectGetMinY(self.topView.frame) - CGRectGetHeight(self.xinqingBtn.frame) + 5,
                                               CGRectGetWidth(self.xinqingBtn.frame), CGRectGetHeight(self.xinqingBtn.frame));
        });
//    }
}

- (void)updatePosition:(BOOL)hideSystemKeyboard
{
    if (hideSystemKeyboard) {
        [self.placeholdView removeFromSuperview];
    } else {
//        if (!self.placeholdView) {
//            self.placeholdView = self.tempView;
//        }
        [self addSubview:self.placeholdView];
        [self updateInputViewHeight];
//        NSString* text = self.inputTV.text;
//        self.inputTV.text = [NSString stringWithFormat:@"%@ ", text];
//        self.inputTV.text = text;
    }
}
@end
